<?php

namespace app\common\model;

use app\common\util\Tools;
use Qcloud\Cos\Client;
use think\Model;

/**
 * Class Auth
 * @package app\common\model
 * 静态资源表
 */
class trResource extends Model
{
    protected $pk = 'id';
    protected $resultSetType = 'collection'; //申明结果集是数据集对象（collection），查询结果才能用toArray()方法转为数组
    protected $name = "resource"; //表名
    static $cacheKey = "resourceCache";

    protected $type = [
        'time'  =>  'timestamp:Y-m-d H:i',
    ];

    protected $ResourceType = [ //类型：1图片；2源码文件；3普通文件
        '1'  =>  '图片',
        '2'  =>  '源码文件',
        '3'  =>  '普通文件',
    ];

    //分页获取所有字段数据
    public static function getListByPaginate($filter = [], $page = 1, $limit = 10, $order = "time desc"){
        $data = self::where($filter)
            ->order($order)
            ->paginate(array('page' => $page, 'list_rows' => $limit));
        if($data){
            $data = $data->toArray();
            $data["data"] = Tools::transferFields($data["data"]);
            return $data;
        }
        return [];
    }

    //添加
    public static function add($data){
        if(!$data)
            return true;
        $data["mall_id"] = request()->mallData["id"];
        if(self::insert($data)){
            C_set($data["mall_id"]."_".self::$cacheKey.$data["id"], $data["url"]);
            return true;
        }
    }

    //得到某字段的一个值
    public static function getValue($field, $filter = []){
        $filter["mall_id"] = request()->mallData["id"];
        if($field == "url"){
            if(isset($filter["id"])){
                $id = $filter["id"];
            }else{
                $id = self::getValue("id", $filter);
            }
            $value = C_get($filter["mall_id"]."_".self::$cacheKey.$id);
            if($value === false){
                $value = self::where($filter)->value($field);
                C_set($filter["mall_id"]."_".self::$cacheKey.$id, $value);
            }
            return $value ?: $id;
        }
        return self::where($filter)->value($field);
    }

    //获取某字段的所有值
    public static function getColumn($field, $filter = [], $key = ''){
        if(!is_array($field)){
            if(!isset($filter[0])) {
                $filter["mall_id"] = request()->mallData["id"];
            }
            return self::where($filter)->column($field, $key);
        }
        return [];
    }

    //软删除
    public static function delSoftById($id){
        if(is_array($id)){
            $result = self::where('id', 'in', $id)->where("mall_id", request()->mallData["id"])->update(["is_delete" => 1]);
        }else{
            $result = self::where('id', $id)->where("mall_id", request()->mallData["id"])->update(["is_delete" => 1]);
        }
        return $result;
    }

    //真实删除
    public static function delById($id, $del = false){
        $filter[] = ["mall_id", "=", request()->mallData["id"]];
        if(!$del){
            $filter[] = ["is_delete", "=", 1];
        }
        if(is_array($id)){
            $filter[] = ['id', 'in', $id];
        }else{
            $filter[] = ['id', '=', $id];
            $id = array($id);
        }
        $image_url = self::getColumn("url", $filter);
        $result = self::where($filter)->delete();
        if($result){
            foreach ($image_url as $url){
                $url = tome_dia($url, false);
                if(is_file($url)){
                    unlink($url);
                }else{
                    static $client;
                    if(empty($client["object"])){
                        $client["config"] = config("thirdConfig.QCloudConfig");
                        $client["object"] = new Client([
                            'region' => $client["config"]["region"], #地域，如ap-guangzhou,ap-beijing-1
                            'credentials' => array(
                                'secretId' => $client["config"]["secretId"],
                                'secretKey' => $client["config"]["secretKey"],
                            ),
                        ]);
                    }
                    $targetDir = substr($url, strpos($url, "://")+3);
                    try {
                        $client["object"]->deleteObject(array(
                            'Bucket' => $client["config"]["bucket"],
                            'Key' => substr($targetDir, strpos($targetDir, "/")+1)
                        ));
                    } catch (\Exception $e) {}
                }
            }
            array_map(function ($value){
                C_set(request()->mallData["id"]."_".self::$cacheKey.$value, null);
            }, $id);
        }
        return $result;
    }

    //真实删除
    public static function delByUrl($params, $del = false){
        $filter[] = ["mall_id", "=", request()->mallData["id"]];
        if(!$del){
            $filter[] = ["is_delete", "=", 1];
        }
        if(is_array($params)){
            $filter[] = ['url', 'in', $params];
        }else{
            $filter[] = ['url', '=', $params];
            $params = array($params);
        }
        $result = self::where($filter)->delete();
        if($result) {
            foreach ($params as $url) {
                $url = tome_dia($url, false);
                if (is_file($url)) {
                    unlink($url);
                }else{
                    static $client;
                    if(empty($client["object"])){
                        $client["config"] = config("thirdConfig.QCloudConfig");
                        $client["object"] = new Client([
                            'region' => $client["config"]["region"], #地域，如ap-guangzhou,ap-beijing-1
                            'credentials' => array(
                                'secretId' => $client["config"]["secretId"],
                                'secretKey' => $client["config"]["secretKey"],
                            ),
                        ]);
                    }
                    $targetDir = substr($url, strpos($url, "://")+3);
                    try {
                        $client["object"]->deleteObject(array(
                            'Bucket' => $client["config"]["bucket"],
                            'Key' => substr($targetDir, strpos($targetDir, "/")+1)
                        ));
                    } catch (\Exception $e) {}
                }
            }
        }
        return $result;
    }
}